package com.ctshk.gateway.handler;

import com.ctshk.common.dto.Result;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.web.server.ResponseStatusException;

/**
 * @author 谢诗宏
 * @description 获取异常信息
 * @date 2020/12/10
 */
public abstract class AbstractExceptionHandler {

    private static final int DEFAULT_ERROR_CODE = -1;

    /**
     * 转换异常信息
     * @param ex
     * @return
     */
    protected String formatMessage(Throwable ex) {
        String errorMessage;
        if (ex instanceof NotFoundException) {
            String reason = ((NotFoundException) ex).getReason();
            errorMessage = reason;
        } else if (ex instanceof ResponseStatusException) {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            errorMessage = responseStatusException.getStatus().name();
        } else {
            errorMessage = ex.getMessage();
        }
        return errorMessage;
    }

    protected Result buildErrorMap(int code, String errorMessage, String errorDetail) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(errorMessage);
        result.setErrDesc(errorDetail);
        return result;
    }

}